﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SyncServer_1
{
    class SyncServer_1
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Socket listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
            IPAddress ipAddr = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipEp = new IPEndPoint(ipAddr, 9999);

            // bind
            listenfd.Bind(ipEp);

            // listen
            listenfd.Listen(0);
            Console.WriteLine("服务器启动成功......");
            while (true)
            {
                //Accept
                Socket connfd = listenfd.Accept();
                Console.WriteLine("[服务器] Accept");

                // Recv
                byte[] readBuff = new byte[1024];
                int count = connfd.Receive(readBuff);
                string str = Encoding.UTF8.GetString(readBuff, 0, count);

                Console.WriteLine($"服务器收到: {str}");

                // Send
                byte[] bytes = Encoding.UTF8.GetBytes("echo:" + str);
                connfd.Send(bytes);
            }
        }
    }
}
